import React, { useRef,useEffect,useState } from 'react';
import { Canvas,useFrame } from '@react-three/fiber';
import * as THREE from 'three';

const Tetrahedron = ({ vertices }) => {
    const ref:any = useRef();
    const [geometry, setGeometry] = useState(new THREE.BufferGeometry().setFromPoints(vertices));

    useFrame(() => {
        ref.current.rotation.x += 0.01;
        ref.current.rotation.y += 0.01;
    });

    // 监听vertices变化并更新几何体
    useEffect(() => {
        const geom = new THREE.BufferGeometry().setFromPoints(vertices);
        geom.setIndex([
            0, 1, 2,
            0, 2, 3,
            2, 1, 3,
            0, 3, 1
        ]);
        geom.computeVertexNormals();
        setGeometry(geom);
    }, [vertices]);

    return (
        <mesh ref={ref} geometry={geometry}>
            <meshStandardMaterial color={'orange'} wireframe={true} />
        </mesh>
    );
};

const MeshDemo3: React.FC = () => {
    const vertices = [
        new THREE.Vector3(0, 0, 0),
        new THREE.Vector3(1, 0, 0),
        new THREE.Vector3(0, 1, 0),
        new THREE.Vector3(0, 0, 1)
    ];

    return (
        <Canvas  style={{ width: '100vw', height: '100vh' }}>
            <ambientLight intensity={0.5} />
            <pointLight position={[10, 10, 10]} />
            <Tetrahedron vertices={vertices} />
        </Canvas>
    );
}

export default MeshDemo3;